package com.creatorblue.modules.controller;

import com.creatorblue.common.constant.ScheduleConstants;
import com.creatorblue.modules.domain.SysJob;
import com.creatorblue.common.exception.TaskException;
import com.creatorblue.modules.service.SysJobService;
import com.creatorblue.modules.utils.CronUtils;
import com.creatorblue.modules.utils.HttpResult;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 定时任务，控制层
 * @author huj
 * @create 2022-01-17 10:35
 * @email hujun@creatorblue.com
 */
@RestController
@RequestMapping("/api/sys/job")
public class SysJobController {

    @Autowired
    private SysJobService sysJobService;

    /**
     * 查询定时任务列表
     */
    @GetMapping("/list")
    public HttpResult list(SysJob sysJob) {
        List<SysJob> list = sysJobService.selectJobList(sysJob);
        return HttpResult.ok(list);
    }

    /**
     * 新增定时任务
     * @param sysJob
     * @return
     * @throws SchedulerException
     * @throws TaskException
     */
    @PostMapping("/add")
    public HttpResult add(@RequestBody SysJob sysJob) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(sysJob.getCronExpression())) {
            return HttpResult.error("cron表达式不正确");
        }
        int i = sysJobService.insertJob(sysJob);
        return HttpResult.ok("新增成功" + i);
    }

    /**
     * 定时任务状态修改（暂停任务 或 恢复任务）
     */
    //@PutMapping("/changeStatus")
    public int changeStatus(@RequestBody SysJob job) throws SchedulerException {
        SysJob newJob = sysJobService.selectJobById(job.getJobId());
        if (newJob != null) {
            if (ScheduleConstants.Status.NORMAL.getValue().equals(newJob.getStatus())) {
                return sysJobService.resumeJob(job);
            } else if (ScheduleConstants.Status.PAUSE.getValue().equals(newJob.getStatus())){
                return sysJobService.pauseJob(job);
            }
        }
        return 0;
    }


    @Autowired
    private Scheduler scheduler;

    @PostMapping("/changeStatus2")
    public int changeStatus2(String jobId, String jobGroup) throws SchedulerException {
        jobGroup = jobGroup == null || jobGroup.trim() == "" ? "jobGroup1" : jobGroup;
        try {
            System.out.println("执行暂定任务的代码 begin");

            JobKey jobKey = new JobKey(jobId, jobGroup);
            scheduler.pauseJob(jobKey);
            System.out.println("执行暂定任务的代码 end");
        } catch (Exception e) {
            System.out.println("系统异常" + e);
        }
        return 0;
    }
}
